<template>
  <div class="harmonic-chart">
    <ECharts :options="chartOptions" :height="height" :width="width" />
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import ECharts from "@/components/ECharts/index.vue";
import type { HarmonicDataItem } from "@/api/hmi/chart.api";
import type { EChartsCoreOption } from "echarts/core";

interface Props {
  /** 谐波数据 */
  data: HarmonicDataItem;
  /** 图表宽度 */
  width?: string;
  /** 图表高度 */
  height?: string;
  /** 图表标题 */
  title?: string;
}

const props = withDefaults(defineProps<Props>(), {
  width: "100%",
  height: "400px",
  title: "",
});

// 计算图表配置
const chartOptions = computed<EChartsCoreOption>(() => {
  const { data } = props;

  if (!data || !data.Bar || data.Bar.length === 0) {
    return {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
      },
    };
  }

  // 准备数据
  const categories = data.Bar.map((item) => item.BarName);
  const values = data.Bar.map((item) => item.Value);
  const maxValues = data.Bar.map((item) => item.MaxValue);

  return {
    title: {
      text: props.title || data.Name,
      left: "center",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex;
        const barItem = data.Bar[dataIndex];
        return `
          <div>
            <strong>${barItem.BarName}</strong><br/>
            别名: ${barItem.BarAlias}<br/>
            当前值: ${barItem.Value} ${barItem.BarDim}<br/>
            最大值: ${barItem.MaxValue} ${barItem.BarDim}
          </div>
        `;
      },
    },
    legend: {
      // data: ["当前值", "最大值"],
      data: ["当前值"],
      top: 30,
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "15%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: categories,
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      name: data.Bar[0]?.BarDim || "",
    },
    series: [
      {
        name: "当前值",
        type: "bar",
        data: values,
        itemStyle: {
          color: "#409EFF",
        },
        emphasis: {
          itemStyle: {
            color: "#66B1FF",
          },
        },
      },
      // {
      //   name: "最大值",
      //   type: "bar",
      //   data: maxValues,
      //   itemStyle: {
      //     color: "#E6F7FF",
      //     borderColor: "#409EFF",
      //     borderWidth: 1,
      //   },
      //   emphasis: {
      //     itemStyle: {
      //       color: "#BAE7FF",
      //     },
      //   },
      // },
    ],
  };
});
</script>

<style scoped>
.harmonic-chart {
  width: 100%;
  height: 100%;
}
</style>
